
import UIKit
import WebKit
typealias webViewHtmlBlock = (_ height: CGFloat ) -> Void

typealias dellDidSelectBlock = (_ rom: NSInteger ) -> Void
typealias dellDidSelectAndStateBlock = (_ rom: NSInteger, _ state:Bool ) -> Void

class TalkfunTestPaperDetailsCell: UICollectionViewCell ,UICollectionViewDelegate, UICollectionViewDataSource ,UICollectionViewDelegateFlowLayout , WKUIDelegate, WKNavigationDelegate
{
    var scrollView:UIScrollView =  UIScrollView.init()
    var pageType:TalkfunQuestionnairePageStatus =  TalkfunQuestionnairePageStatusOnePage

    var collectionViewH:CGFloat = 0.0
    let scrollViewBackgroundColor = UIView()
    let testPaperDetailslReply = TalkfunTestPaperDetailslReply()
    var webView = WKWebView.init()
    /**必选星*/
    var requiredLabel = UILabel.init()
    
    //解析webView
    var analysisWebView = WKWebView.init()
    //虚线
    let dottedLine = TalkfunDottedLine()
    //解析label
    var analysisLabel:UILabel = UILabel.init()
    //答案
    @objc public let answerTextLabel = UILabel.init()
    var webViewHeightBlock: webViewHtmlBlock?
    var analysisHeightBlock: webViewHtmlBlock?

    var selectAndStateBlock: dellDidSelectAndStateBlock?
    var testPaperDetailsSelectBlock:TestPaperDetailsSelectBlock?
    //考试是否结束
    var isEndOfTestPaper:Bool = false
    @objc public let textLabel:UILabel = UILabel.init()
    @objc public let typtTextLabel:UILabel = UILabel.init()
    
    @objc public weak var delegate : TalkfunTestPaperDetailsCellDelegate?
    //未作答
    let unanswered = UILabel()
    let collectionView = UICollectionView.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0), collectionViewLayout: UICollectionViewFlowLayout())
    let TalkfunOptionsDecideCollectionViewCell_ID = "TalkfunOptionsDecideCollectionViewCell_ID"
          var isAddFillet: Bool = false
    @objc public var optionsList = NSMutableArray()
    /**2:随堂考 3.问卷 4.快速答题卡*/
    @objc public var subjectExamineInfoType:TFExaminationType = TFExaminationTypeTestPaper
    var model:TalkfunSubjectExamineDetail? {
        didSet {
            if ((model) != nil)
            {
                self.scrollView.frame = CGRect(x: 12.0, y: 0, width: self.scrollViewWidth(), height: self.frame.height);
               
                var testPaperDetailslReplyH = 0.0
                //:随堂考
                if(self.isEndOfTestPaper && self.subjectExamineInfoType == TFExaminationTypeTestPaper)
                {
                    //解析
                    self.analysisWebView.isUserInteractionEnabled = false
                    
                    self.analysisLabel.isHidden = false
                    self.analysisWebView.isHidden = self.analysisLabel.isHidden
                }else{
                    //解析
                    self.analysisWebView.isUserInteractionEnabled = true
                    
                //课程未结束
                self.analysisLabel.isHidden = true
                self.analysisWebView.isHidden = self.analysisLabel.isHidden
                }
               
                //题目类型：1单选题、2多选题、3判断题、4填空题、5问答题
                if (model?.subjectInfo.type == TalkfunTopicTypeIndividualEvent )
                {
                    self.typtTextLabelAttributed(text: "单选题")
                }else if (model!.subjectInfo.type == TalkfunTopicTypeMultiple )
                {
                    self.typtTextLabelAttributed(text: "多选题")
                }else if (model?.subjectInfo.type == TalkfunTopicTypeJudgment )
                {
                    self.typtTextLabelAttributed(text: "判断题")
                }
                else if (model?.subjectInfo.type == TalkfunTopicTypeStuff )
                {
                    self.typtTextLabelAttributed(text: "填空题")
                   
                }
                else if (model?.subjectInfo.type == TalkfunTopicTypeShortAnswer )
                {
                    //简答题
                    self.typtTextLabelAttributed(text: "简答题")
                }

                let titleStr = model?.subjectInfo.subject

                
                self.setHtmlHeight(width: self.cellWidth(), html: titleStr! as NSString,webViewHeight:model!.titleWebViewHeight)
                
                let isRequired:Bool = model!.subjectInfo.isRequired
                //必选
                if (isRequired == true) {
                    self.requiredLabel.isHidden = false
                }else
                {
                    self.requiredLabel.isHidden = true
                }
                
                
                self.optionsList.removeAllObjects()
                let optionsList = NSMutableArray.init(array: model!.subjectAnswerList as NSArray)

                self.optionsList = optionsList
                
                let testPaperDetailslReplyY = self.webView.frame.maxY
                
                
                let subjectInfoType = model!.subjectInfo.type;

                //计算回复选项的高度
                testPaperDetailslReplyH = TalkfunTestPaperDetails.getOptionsListHightFilling(model: model!)
                
                
                //回复专用view(可能 有多个回复选项)
                self.testPaperDetailslReply.frame = CGRect(x: 12.0, y: testPaperDetailslReplyY, width: self.scrollView.frame.width - 12.0 - 12.0, height: testPaperDetailslReplyH)
                
                
                 //内部有table
                self.testPaperDetailslReply.options(list: model!.subjectAnswerList,isEndOfTestPaper: self.isEndOfTestPaper)
                
                //默认是隐藏
                self.testPaperDetailslReply.textView.isHidden = true
                self.testPaperDetailslReply.textView.text = ""
                //简答题才显示
                if (subjectInfoType == TalkfunTopicTypeShortAnswer ) {
                    self.testPaperDetailslReply.textView.isHidden = false
                   
                    if  (model!.subjectExamineAnswerDetailInfo.answer.count) > 0  {

                        let text:NSString =  model!.subjectExamineAnswerDetailInfo.answer[0] as! NSString

                        self.testPaperDetailslReply.textView.text = text as String
                    }
                    
                    if self.isEndOfTestPaper {
                        self.testPaperDetailslReply.textView.isEditable = false
                    }else
                    {
                        self.testPaperDetailslReply.textView.isEditable = true
                    }
                    
                }
                
                var height = 0.0
                
                
                var textLabelW = self.webView.frame.width - 16.0 - 16.0
                if (self.model!.subjectInfo.type == TalkfunTopicTypeStuff)
                {
                    textLabelW = self.webView.frame.width - 64.0 - 16.0
                }
                //不等于 填空题4 或者课程结束了
                height = height +  TalkfunTestPaperDetails.getOptionHeight(model2: model!, isEndOfTestPaper:self.isEndOfTestPaper, textLabelW: textLabelW)

               
                let webViewMaxY = self.testPaperDetailslReply.frame.maxY
                let webViewWidth = self.webView.frame.width
                let collectionViewY = webViewMaxY + 15.0
            
                self.collectionView.frame = CGRect(x: 12.0, y: collectionViewY, width:webViewWidth , height: height)

                var contentSizeH = 0.0
                if (self.isEndOfTestPaper == true)
                {
                    let analysis = model!.subjectInfo.analysis as NSString

                        var x = 0.0
                    ///**1单选题、2多选题、3判断题、4填空题、5问答题*/
                    if (model!.subjectInfo.type != TalkfunTopicTypeStuff)
                        {
                            x = 16.0
                        }

                    let answerTextLabelY = collectionViewY + height + 10.0

                    var  str = "" as NSString
                    //Correct option
                    for i in stride(from: 0, to: (model?.subjectAnswerList.count)! ,by: 1) {
                        
                        let cell = model?.subjectAnswerList[i] as! TalkfunSubjectAnswer
                        
                        if(cell.isCorrect == true)
                        {
                            //A.   选项题目 + 前缀
                            let prefix = TalkfunSharedTools.asciiBytesToString(inx: i) 
                            if(str.length == 0)
                            {
                                str = prefix as NSString
                            }else
                            {
                                str = str as String + "." + prefix as NSString
                            }
                           

                        }
                      
                    }
                    
                    var unansweredY = answerTextLabelY
                    if(self.isEndOfTestPaper && (model!.subjectExamineAnswerDetailInfo.answer.count) == 0 && self.subjectExamineInfoType == TFExaminationTypeTestPaper)
                    {
                      
                            unansweredY = answerTextLabelY - 20.0
                            //未作答
                            self.unanswered.frame = CGRect(x: 12.0 , y: unansweredY + 15.0, width: 51.0, height: 24.0)
                            unansweredY = 15.0 + (unansweredY + 24.0) + 40.5
                            self.unanswered.isHidden = false
                        
                       
                    }else if(self.isEndOfTestPaper)
                    {
                        
                        unansweredY = unansweredY + 20.0
                        //未作答
                        self.unanswered.isHidden = true
                    }
                    else
                    {
                        self.unanswered.isHidden = true
                    }
                    
                    //虚线frame
                    self.dottedLine.frame = CGRect(x: 12.0, y: unansweredY - 20.0, width: self.webView.frame.width  , height: 1.0)
                    
                    self.dottedLine.drawDashLine(strokeColor: UIColor.gray)
                    
                        var msg = "【答案】"
                           msg = msg + (str  as String)

                        //非填空题的答案
                        let attrString1 = NSMutableAttributedString(string: msg)
                        let attr1: [NSAttributedString.Key : Any] = [.font: UIFont(name: "PingFang SC", size: 16) as Any,.foregroundColor: UIColor(red: 0.08, green: 0.09, blue: 0.1,alpha:1), ]
                        attrString1.addAttributes(attr1, range: NSRange(location: 0, length: attrString1.length))
                        self.answerTextLabel.attributedText = attrString1
                        self.answerTextLabel.frame = CGRect(x:  12.0 + x, y: unansweredY, width: self.webView.frame.width - (12.0 + x), height: 23)


                        //5.0 是与上面的间距
                        let analysisWebViewX = 64.0 + 12.0 + x
                        var analysisWebViewY = unansweredY + 23 + 10.0
                        //填空
                    if (model!.subjectInfo.type == TalkfunTopicTypeStuff){
                            analysisWebViewY = unansweredY
                            self.answerTextLabel.isHidden = true
                            self.dottedLine.isHidden = true
                        }else{
                            analysisWebViewY = unansweredY + 23 + 10.0
                            
                            //结束的随堂考才显示
                            if self.subjectExamineInfoType == TFExaminationTypeTestPaper {
                                self.answerTextLabel.isHidden = false
                                self.dottedLine.isHidden = false
                            } else if(self.subjectExamineInfoType == TFExaminationTypeTable)
                            {
                                self.answerTextLabel.isHidden = true
                                self.dottedLine.isHidden = true
                            }
                            
                        }
                    
          
                        self.analysisWebView.frame = CGRect(x:analysisWebViewX, y:analysisWebViewY , width: webViewWidth - 64.0  , height: model!.analysisWebViewHeight)
                        let headerString = "<header><meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no'><style>img{max-width:100%}</style></header>";
                        let newS = (headerString as String) + (analysis as String)
                        self.analysisWebView.loadHTMLString(newS as String , baseURL: nil)

                        
                        self.analysisLabel.frame = CGRect(x: 12.0 + x, y: analysisWebViewY, width: 64.0, height: 23)

                    contentSizeH = self.analysisWebView.frame.origin.y + self.analysisWebView.frame.size.height
                }
                else{
                    self.answerTextLabel.isHidden = true
                    self.dottedLine.isHidden = true
                    self.unanswered.isHidden = true
                    contentSizeH = self.collectionView.frame.origin.y + self.collectionView.frame.size.height
                }
                
                
                
                
                let spacing = 36.0
        
                //分页
                if (self.pageType == TalkfunQuestionnairePageStatusPagination) {
                    if (self.isEndOfTestPaper == true)
                    {
                       
                    }else
                    {
                        //未结束
                        contentSizeH = model!.cellHeight
                      
                    }
                    self.scrollView.backgroundColor = UIColor.clear
                    self.backgroundColor = UIColor.clear
                    self.scrollViewBackgroundColor.backgroundColor = UIColor.white
                    self.scrollView.isScrollEnabled = true
                }else
                {
                    self.scrollView.isScrollEnabled = false
                    //一页
                    self.scrollView.backgroundColor = UIColor.clear
                    self.backgroundColor = UIColor.clear
                    self.scrollViewBackgroundColor.backgroundColor = UIColor.white
                }
            
                
                self.scrollViewBackgroundColor.frame = CGRect(x: 0, y: 0, width: self.scrollView.frame.width, height:contentSizeH )
                self.scrollView.contentSize = CGSize(width: 0, height:contentSizeH + spacing )
                self.scrollView.setContentOffset(CGPoint(x: 0, y: 0), animated: false)
               
                self.collectionView.reloadData()
            }
        
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.addSubview(self.scrollView)
        self.scrollView.addSubview(self.scrollViewBackgroundColor)
        self.scrollView.layer.cornerRadius = 4
        self.scrollView.layer.masksToBounds = true
        
        self.backgroundColor = UIColor.clear
        
        self.scrollView.addSubview(self.webView)
        self.webView.uiDelegate = self
        self.webView.navigationDelegate = self
        self.webView.backgroundColor = UIColor.clear
        self.webView.scrollView.isScrollEnabled = false
        self.webView.isUserInteractionEnabled = false
        
        self.requiredLabel.text = "*"
        self.requiredLabel.font = UIFont.PingFang(size: 13)
        self.requiredLabel.textColor = UIColor.red
        self.requiredLabel.backgroundColor = UIColor.clear
        self.webView.addSubview(self.requiredLabel)
        
        
        self.scrollView.addSubview(self.testPaperDetailslReply)
        
        //第1题
        self.textLabel.textAlignment = NSTextAlignment.center
        self.textLabel.lineBreakMode = NSLineBreakMode.byCharWrapping;
        self.scrollView.addSubview(self.textLabel)
        self.textLabel.numberOfLines = 0
        //单选题
        self.typtTextLabel.textAlignment = NSTextAlignment.center
        self.typtTextLabel.lineBreakMode = NSLineBreakMode.byCharWrapping;
        self.scrollView.addSubview(self.typtTextLabel)
        self.typtTextLabel.layer.masksToBounds = true

        if #available(iOS 11.0, *) {
            self.scrollView.contentInsetAdjustmentBehavior = .never
            self.collectionView.contentInsetAdjustmentBehavior = .never
            }
        self.scrollView.addSubview(self.collectionView)
        self.collectionView.isScrollEnabled = false
        self.collectionView.dataSource = self
        self.collectionView.delegate = self
        self.collectionView.register(TalkfunOptionsDecideCollectionViewCell.self, forCellWithReuseIdentifier:TalkfunOptionsDecideCollectionViewCell_ID)

        self.collectionView.backgroundColor = UIColor.clear
        self.scrollView.addSubview(self.analysisWebView)
        self.analysisWebView.uiDelegate = self
        self.analysisWebView.navigationDelegate = self
        self.analysisWebView.backgroundColor = UIColor.clear
        self.analysisWebView.scrollView.isScrollEnabled = false
        
        let unansweredAttrString = NSMutableAttributedString(string: "未作答")
        self.unanswered.numberOfLines = 0
        let unansweredAttr: [NSAttributedString.Key : Any] = [.font: UIFont(name: "PingFang SC", size: 17)as Any,.foregroundColor: UIColor(red: 1, green: 0.33, blue: 0.33,alpha:1), ]
        unansweredAttrString.addAttributes(unansweredAttr, range: NSRange(location: 0, length: unansweredAttrString.length))
        self.unanswered.attributedText = unansweredAttrString
        self.scrollView.addSubview(self.unanswered)
        self.unanswered.isHidden = false

        self.dottedLine.backgroundColor = UIColor.clear
        //虚线
        self.scrollView.addSubview(self.dottedLine)
         //答案
        self.answerTextLabel.numberOfLines = 0
        self.scrollView.addSubview(self.answerTextLabel)
        self.answerTextLabel.backgroundColor = UIColor.clear
        self.scrollView.addSubview(self.textLabel)
        
        let attrString = NSMutableAttributedString(string: "【解析】")
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont(name: "PingFang SC", size: 16) as Any,.foregroundColor: UIColor(red: 0.08, green: 0.09, blue: 0.1,alpha:1), ]
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        self.analysisLabel.attributedText = attrString
        self.analysisLabel.numberOfLines = 0
        self.analysisLabel.backgroundColor = UIColor.white
        self.scrollView.addSubview(self.analysisLabel)
    }
    func scrollViewWidth()->CGFloat
    {
        return self.frame.width - 12.0 - 12.0
    }
    func cellWidth()->CGFloat
    {
        return self.scrollViewWidth() - 12.0 - 12.0
    }
    @objc  func textLabelAttrString(text:NSString)
    {
        let textLabelAttr = NSMutableAttributedString(string:text as String)
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont(name: "PingFang SC", size: 17)as Any ,.foregroundColor: UIColor.gray, ]
        textLabelAttr.addAttributes(attr, range: NSRange(location: 0, length: textLabelAttr.length))
        self.textLabel.attributedText = textLabelAttr
        

        let textLabelStrSize = TalkfunSharedTools.getSizeLabel(labelString: textLabelAttr, labelWidth:self.cellWidth(), labelfont: UIFont(name: "PingFang SC", size: 17)!)
        self.textLabel.frame = CGRect(x: 12, y: 20, width: textLabelStrSize.width, height: 24)
        
    }
    func typtTextLabelAttributed(text:NSString)
    {
        let typtTextLabelAttrString = NSMutableAttributedString(string: text as String)
        self.typtTextLabel.numberOfLines = 0
        let typtTextLabelAttr: [NSAttributedString.Key : Any] = [.font: UIFont(name: "PingFang SC", size: 13) as Any ,.foregroundColor: UIColor(red: 0.25, green: 0.59, blue: 0.92,alpha:1), ]
        typtTextLabelAttrString.addAttributes(typtTextLabelAttr, range: NSRange(location: 0, length: typtTextLabelAttrString.length))
        self.typtTextLabel.attributedText = typtTextLabelAttrString
        self.scrollView.addSubview(self.typtTextLabel)
        self.typtTextLabel.backgroundColor = UIColor(red: 0.92, green: 0.96, blue: 1, alpha: 1)
        
        self.typtTextLabel.frame = CGRect(x:  self.textLabel.frame.maxX + 20.0, y: 21.0, width: 49.0, height: 22.0)
        if (self.isAddFillet == false)
        {
            let maskPath = UIBezierPath.init(roundedRect: self.typtTextLabel.bounds, byRoundingCorners:[UIRectCorner.bottomLeft,UIRectCorner.topRight], cornerRadii: CGSize(width: 11, height: 11))
            
            let  maskLayer = CAShapeLayer()
            maskLayer.frame = self.typtTextLabel.bounds
            maskLayer.path = maskPath.cgPath
            
            self.typtTextLabel.layer.mask = maskLayer
            self.isAddFillet = true
        }
    }
    
    @objc static func getTitleFont() ->UIFont
    {
        return UIFont(name: "PingFang SC", size: 17)!
    }

    func heightForRowAt(model2:TalkfunSubjectAnswer) ->CGFloat
    {

        var prefix = TalkfunSharedTools.asciiBytesToString(inx: 1) + "."
        if (self.model!.subjectInfo.type == TalkfunTopicTypeStuff)
         {
             prefix = ""
         }
        var msg = prefix + model2.answer
        
        var labelWidth = self.webView.frame.width - 16.0 - 16.0
        
        

        
        
        
        if (self.model!.subjectInfo.type == TalkfunTopicTypeStuff)
        {
            labelWidth = self.webView.frame.width - 64.0 - 16.0
        }
        //表单
        if self.subjectExamineInfoType == TFExaminationTypeTable {
            msg = model2.answer
            
            labelWidth = self.webView.frame.width - 38.0 - 16.0
        }
        
        let sizeLabelHightAndSpacing = TalkfunTestPaperDetails.getsizeLabelHightAndSpacing(msg: msg as NSString, textLabelW: labelWidth, model: self.model! )
        
        return sizeLabelHightAndSpacing
    }
  
    //TODO: 数据源
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.optionsList.count
    }
    //TODO: cell的创建
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: TalkfunOptionsDecideCollectionViewCell_ID, for: indexPath) as! TalkfunOptionsDecideCollectionViewCell

        
        let model = self.optionsList[indexPath.row] as! TalkfunSubjectAnswer
        
        // /**2:随堂考 3.问卷 4.快速答题卡*/
        cell.subjectExamineInfoType = self.subjectExamineInfoType;
        
        cell.updateUI(model: model, type:(self.model?.subjectInfo.type)! as TalkfunTopicType , isEndOfTestPaper:self.isEndOfTestPaper, row: indexPath.row)
      

       return cell
        
      
    }
    //TODO: UICollectionViewCell高度
    func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: UICollectionViewLayout,
                        sizeForItemAt indexPath: IndexPath) -> CGSize
    {

        if (indexPath.row >= self.optionsList.count) {
            return  CGSize(width: self.collectionView.frame.size.width, height: 0.0)
        }
        
       let model = self.optionsList[indexPath.row] as! TalkfunSubjectAnswer

        var textLabelX = 16.0
        //填空
        if (self.model?.subjectInfo.type == TalkfunTopicTypeStuff )
        {
            textLabelX = 64.0
            let titleAttrString = NSMutableAttributedString(string: model.answer as String)

            let sizeLabel = TalkfunSharedTools.getSizeLabel(labelString: titleAttrString, labelWidth: self.scrollView.frame.width - textLabelX , labelfont: UIFont(name: "PingFang SC", size: 16)! )
            
            return  CGSize(width: self.collectionView.frame.size.width, height: sizeLabel.height + TalkfunSharedTools.getOptionsCellLineSpacing(model: self.model!))
        }
        else
        {
 
            return  CGSize(width: self.collectionView.frame.size.width, height: self.heightForRowAt(model2: model))
            
        }
       
    }
    //TODO: 點選 cell 後執行的動作
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        
//        self.delegate?.responds(to: #selector(TalkfunTestPaperDetailsCellDelegate.getSuperviewIsEndOfTestPaper))
       var IsEndOfTestPaper = self.isEndOfTestPaper
        if self.delegate != nil && (self.delegate?.responds(to: #selector(TalkfunTestPaperDetailsCellDelegate.getSuperviewIsEndOfTestPaper) )   )!{
            
            IsEndOfTestPaper = (self.delegate!.getSuperviewIsEndOfTestPaper())
            
        }
        
        
        if(IsEndOfTestPaper)
        {
            return
        }
        let subjectAnswer = self.optionsList[indexPath.row] as! TalkfunSubjectAnswer
        //"单选题" 判断题
        if (self.model?.subjectInfo.type == TalkfunTopicTypeIndividualEvent || self.model?.subjectInfo.type == TalkfunTopicTypeJudgment )
        {
            for obj in self.optionsList {
            let options = obj as! TalkfunSubjectAnswer
                options.isSelected = false
            }
            subjectAnswer.isSelected = !subjectAnswer.isSelected
        }else if (self.model?.subjectInfo.type == TalkfunTopicTypeMultiple )
        {
       // "多选题")
            subjectAnswer.isSelected = !subjectAnswer.isSelected
        }
        else if (self.model?.subjectInfo.type == TalkfunTopicTypeStuff )
        {
        //  "填空题")
       
        }
        
        //已经选中的选项 id
        let selected_id_list = NSMutableArray.init()
        for obj in self.optionsList {
        let options = obj as! TalkfunSubjectAnswer
            if (options.isSelected == true)
            {
                let ID =  NSString(format: "%i", options.id)
                selected_id_list.add(ID)
            }
            
        }
        
        self.collectionView.reloadData()
        
        var isSelected = false
        for obj in self.optionsList {
            let subjectAnswer1 = obj as! TalkfunSubjectAnswer
            
            if(subjectAnswer1.isSelected == true)
            {
                isSelected = true
            }
        }
        
          print("详情的第 \(indexPath.item ) 張圖片")
        if self.selectAndStateBlock != nil {
            self.selectAndStateBlock!(self.tag ,isSelected)
        }
        
        //选项请求
        if self.testPaperDetailsSelectBlock != nil {
            //题目id
            let subjectId = self.model!.subjectId as NSInteger

            self.testPaperDetailsSelectBlock!(subjectId,selected_id_list,"", "")
        }
    }
    // cell与上下间距
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
     
        return self.getSpacing()
    }
    
    func getSpacing()->CGFloat
    {
        ///**1单选题、2多选题、3判断题、4填空题、5问答题*/
        if (self.model?.subjectInfo.type == TalkfunTopicTypeStuff )
        {
            return 5.0
        }
        return 15.0
    }

    @objc  func setHtmlHeight(width:CGFloat ,html:NSString ,webViewHeight:CGFloat)
    {
        //模拟的数据
//        let newHtml = "<p>1+1=<input class=\"symbol_answer\" time=\"1639647170091\" \" style=\"border: none;display:inline-block;outline: none;width: 42px;border-bottom: 1px solid #333;font-size: 14px;background: transparent\" value=\"（1）\" data-index=\"1\"/>&nbsp; &nbsp; &nbsp; 2+2=<input class=\"symbol_answer\" time=\"1639647176903\" \" style=\"border: none;display:inline-block;outline: none;width: 42px;border-bottom: 1px solid #333;font-size: 14px;background: transparent\" value=\"（2）\" data-index=\"2\"/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;3+3=<input class=\"symbol_answer\" time=\"1639647183806\" \" style=\"border: none;display:inline-block;outline: none;width: 42px;border-bottom: 1px solid #333;font-size: 14px;background: transparent\" value=\"（3）\" data-index=\"3\"/></p><p><img src=\"https://s2.talk-fun.com/4/image/88/e4/ac/72f9d20cdbadba7148c53619dd.jpg\" title=\"\" alt=\"\"/></p>"
//        
        let headerString = "<header><meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no'><style>img{max-width:100%}</style></header>";
        
        let newS = (headerString as String)  + (html as String)
        
        self.webView.loadHTMLString(newS , baseURL: nil)
        self.webView.frame = CGRect(x: 12.0, y: 54.0 , width: width, height: webViewHeight)
        
        
        self.requiredLabel.frame = CGRect(x: 0, y: 8, width: 10, height: 10)
        
        let script = WKUserScript(source: "var getInputValue = function () {var doms = document.getElementsByTagName('input'); var domArrs = Array.prototype.slice.call(doms); var results = domArrs.map(function (item) {return item.getAttribute('value') || null}) return JSON.stringify(results)}",injectionTime: .atDocumentStart, forMainFrameOnly: true)
        self.webView.configuration.userContentController.addUserScript(script)
        
        
        let source1 = "var setInputValue = function(vals) {var doms = document.getElementsByTagName('input');vals.forEach(function(item,index){if(doms[index]){doms[index].value = item;}})}"
        
        let script1 = WKUserScript(source: source1,injectionTime: .atDocumentStart, forMainFrameOnly: true)
        //往HTML里面注入脚本
        self.webView.configuration.userContentController.addUserScript(script1)
    }
    // // 页面加载完成之后调用
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        if(webView == self.webView )
       {
            
            webView.evaluateJavaScript("document.body.scrollHeight") { (value, error) in
                
              let  webViewHeight = CGFloat(value as! CGFloat)
             
                if self.webViewHeightBlock != nil {
                    
                    self.webViewHeightBlock!(webViewHeight )
                }
            }
            
            
        }
        
     
        else if(webView == self.analysisWebView)
            {
                webView.evaluateJavaScript("document.body.scrollHeight") { (value, error) in

                      let  webViewHeight = CGFloat(value as! CGFloat)


                        if self.analysisHeightBlock != nil {
                            self.analysisHeightBlock!(webViewHeight)
                        }


                }
            }
   
    }
    
    // 页面加载失败时调用
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {

        
    }
    
    func getgetInputValue()
    {
        self.webView.evaluateJavaScript("getInputValue()", completionHandler: { (value, error) in
      
        })
        
        self.webView.evaluateJavaScript("setInputValue([6,7,8])", completionHandler: { (value, error) in
         
        })
        
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
 

}
@objc protocol TalkfunTestPaperDetailsCellDelegate : NSObjectProtocol {
    
    func  getSuperviewIsEndOfTestPaper()->Bool
    

}
